import { getAll, saveOrUpdate,deleteMenu,getEdidMenuInfo} from "@/api/menus"
import router from "@/router/index"
import { ref, computed } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
export function useMenus() {
    const allMenus = ref([])
    const getAllMenus = async () => {
             const { data } = await getAll()
        if (data.code === "000000") {
            allMenus.value = data.data
            console.log('allMenus', allMenus.value)
        } else {
            ElMessage.error('获取所有菜单失败..')
            throw new Error('获取所有菜单失败')
        }
    }
    const topMenus = computed(() =>
        allMenus.value.filter(menu => Number(menu.level) === 0)
    )
    const form = ref({
        name: '',
        href: '',
        parentId: -1,
        description: "",
        icon: "",
        orderNum: 0,
        shown: true,
    })

    const onSubmit = async () => {
        const {data} = await saveOrUpdate(form.value)
        console.log(data)
        if (data.code === '000000'){
           
            ElMessage.success(`${msgText.value}菜单成功`)
            router.push({ name: "menus" })
            
        } else {
            ElMessage.error(`${msgText.value}菜单失败`)
            throw new Error(`${msgText.value}菜单失败！`)
        }
    }

    //删除菜单
    const handleDelete = async (id) => {
        await ElMessageBox.confirm("确认要删除该菜单吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
        }).catch(() => {
            ElMessage.info("已取消删除")
            //点取消的话生成一个新的promise处于pendding不让他继续往下执行
            return new Promise(() => {})  
        })

        //调用接口函数
       if (data.code === '000000' && data.data) {
        ElMessage.success("删除菜单成功")
         getAllMenus()
       } else {
        ElMessage.error("删除菜单失败")
        throw new Error("删除菜单失败！")
       }
    }
    
    //根据ID获取菜单详情
    const getMenuInfoById = async (id) => {
        //没定义就是undefined = false
        if (!Number(id)){
            isCreate.value = true
            return
        } else {
            isCreate.value = false
        }
     //通过接口获取信息
      const res = await getEdidMenuInfo(id)
      if (data.code === "000000"){
        form.value = data.data.menuInfo
      } else {
        ElMessage.error("获取菜单详情失败")
        throw new Error("获取菜单详情失败！")
      }
    }
    //状态与提示文字
    const isCreate = ref(true)
    //跟着变就用computed
    const msgText = computed( () => ( isCreate.value ? "新增" : "编辑"))

    return { allMenus, getAllMenus, topMenus, form, onSubmit ,handleDelete,getMenuInfoById ,msgText}
}